<template>
  <div>
    <div><h1>商品类型</h1></div>
    <div>
      <el-button size="small" type="primary" @click="getAddtype1"
        >添加</el-button
      >
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        default-expand-all
      >
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="name" label="类型名称" />
        <el-table-column prop="typeTop" label="排序" />
        <el-table-column prop="typeStatus" label="状态">
          <template #default="scope">
            <span v-if="scope.row.typeStatus == 0">显示</span>
            <span v-if="scope.row.typeStatus == 1">隐藏</span>
          </template>
        </el-table-column>
        <el-table-column prop="typeImage" label="图片">
          <template #default="scope">
            <img
              v-if="scope.row.typeImage != null"
              :src="scope.row.typeImage"
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="getAddtype(scope.row)"
              >添加</el-button
            >
            <el-button
              type="success"
              size="small"
              @click="getupdatetype(scope.row)"
              >修改</el-button
            >
            <el-button type="danger" size="small" @click="getAddtype(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="分类名称"
            :label-width="formLabelWidth"
            prop="typeName"
          >
            <el-input v-model="form.typeName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="分类图片"
            :label-width="formLabelWidth"
            prop="typeImage"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/shop/type/uploadImage"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="分类排序"
            :label-width="formLabelWidth"
            prop="typeTop"
          >
            <el-input v-model="form.typeTop" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="分类状态"
            :label-width="formLabelWidth"
            prop="typeStatus"
          >
            <el-radio-group v-model="form.typeStatus">
              <el-radio :value="0">显示</el-radio>
              <el-radio :value="1">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              v-if="title == '添加类型表单'"
              type="primary"
              @click="submitForm(ruleFormRef)"
            >
              提交
            </el-button>
            <el-button
              v-if="title == '修改类型表单'"
              type="primary"
              @click="onsubmitUpdate"
            >
              修改
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { TypetreeList, addType, updateType } from "../api/api";

import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
const imageUrl = ref("");
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const ruleFormRef = ref<FormInstance>();
const title = ref("添加类型表单");

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const tableData = ref([]);

const form = ref({
  typeId: null,
  typeImage: "",
  typeName: "",
  typePid: null,
  typeStatus: null,
  typeTop: null,
});

//提交表单

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onsubmitAdd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const checkAge = (rule: any, value: any, callback: any) => {
  if (imageUrl.value == null || imageUrl.value == "") {
    return callback(new Error("请输入图片"));
  } else {
    return callback();
  }
};

//表单校验
const rules = ref({
  typeName: [{ required: true, message: "请输入类型名称", trigger: "blur" }],
  typeStatus: [
    {
      required: true,
      message: "请选择类型状态",
      trigger: "change",
    },
  ],
  typeTop: [{ required: true, message: "请输入排序", trigger: "blur" }],
  typeImage: [{ required: true, validator: checkAge, trigger: "blur" }],
});

//修改类型

const onsubmitUpdate = () => {
  form.value.typeImage = imageUrl.value;
  updateType(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      loadList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//显示修改框
const getupdatetype = (row: any) => {
  title.value = "修改类型表单";
  console.log(row);
  form.value.typeId = row.id;
  form.value.typePid = row.parentId;
  form.value.typeName = row.name;
  imageUrl.value = row.typeImage;
  Object.assign(form.value, row);
  console.log(form.value);
  dialogFormVisible.value = true;
};

//添加类型
const onsubmitAdd = () => {
  form.value.typeImage = imageUrl.value;
  addType(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//上传图片成功函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};

//显示添加框父类
const getAddtype1 = () => {
  title.value = "添加类型表单";
  imageUrl.value = "";
  form.value = {
    typeId: null,
    typeImage: "",
    typeName: "",
    typePid: 0,
    typeStatus: null,
    typeTop: null,
  };
  console.log("添加父类");
  dialogFormVisible.value = true;
};

//显示添加框子类
const getAddtype = (row: any) => {
  title.value = "添加类型表单";
  imageUrl.value = "";
  console.log("添加子类");
  form.value = {
    typeId: null,
    typeImage: "",
    typeName: "",
    typePid: row.id,
    typeStatus: null,
    typeTop: null,
  };
  dialogFormVisible.value = true;
};

const loadList = () => {
  TypetreeList().then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data;
    }
  });
};

onMounted(() => {
  loadList();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
